<?php
/*
 * 广告分类
 */
namespace app\admin\controller;
use app\common\controller\AdminBase;
use think\facade\Db;
use think\facade\Session;
use app\common\model\AdCat as AdCatModel;

class AdCat extends AdminBase
{
    protected function _initialize()
    {
        parent::_initialize();
    }

    public function lists()
    {
        $param = $this->request->param();
        if (!empty($param['title'])) {
            $where = function ($query) use ($param){$query->where('name','LIKE', '%'.trim($param['title']).'%');};
        }else{
           $where = 1;
        }
        $list = AdCatModel::where($where)->paginate();
        return $this->fetch('index',['list'=>$list]);
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $result = AdCatModel::create($param);
            !$result && $this->error($this->errorMsg);
            insert_admin_log('添加了公告');
            $this->success('添加成功');

        }
        return $this->fetch('save');
    }

    public function edit()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            in_array($param['id'], [1,2,3,4]) && $this->error('系统分类，无法修改');
            $result = AdCatModel::update($param);
            !$result && $this->error($this->errorMsg);
            insert_admin_log('修改了公告');
            $this->success('修改成功');
        }
        return $this->fetch('save', ['data' => Db::table('ad_cat')->find(input('id'))]);
    }

    public function del()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            Db::table('advert')->where('ad_cat_id',$param['id'])->find() && $this->error('分类下有广告，无法删除');
            Db::table('advert')->whereIn('ad_cat_id', [1,2,3,4])->select() && $this->error('系统分类，无法删除');
            AdCatModel::destroy($param['id']);
            insert_admin_log('删除了公告');
            $this->success('删除成功');
        }
    }


}
